<!--问题中心编辑-->
<template>
  <div class="m-view-questionEdit" id="ls_questionEdit">
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      width="700px"
      :before-close="handleClose"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :inline-message="true"
    >
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="90px"
        class="edit-ruleForm"
        :rules="rules"
      >
        <el-form-item label="标题:" class="rightItem" prop="title">
          <el-input placeholder="输入标题,不超过20个字符" v-model="ruleForm.title" maxlength="20"  show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="问题分类:" class="rightItem" prop="type">
          <el-cascader
            v-model="ruleForm.type"
            :options="parentOptions"
            :props="cascaderProps"
            :show-all-levels="true"
            @change="cascaderChange"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="问题级别:" class="rightItem" prop="priority">
          <el-select v-model="ruleForm.priority" placeholder="请选择优先级">
            <el-option
              v-for="item in priorityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="查看对象:" class="rightItem" prop="traType">
          <el-radio-group v-model="ruleForm.traType">
            <el-radio :label="2">全部</el-radio>
            <el-radio :label="0">供应商</el-radio>
            <el-radio :label="1">内部用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="处理方法:"
          class="rightItem"
          prop="content"
          :show-message="false"
          :error="'sasasa'"
        >
          <lesso-editor v-model="ruleForm.content" :options="editorOptions"></lesso-editor>
        </el-form-item>
        <el-form-item label="附件:" class="rightItem">
          <!-- <el-upload
            class="upload-demo"
            :action="upload_url"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="5"
            :file-list="files"
            :on-change="change"
            :data="userInfo"
            :onSuccess="uploadSuccess"
            :before-upload="beforeAvatarUpload"
            ref="upload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <span
              slot="tip"
              class="el-upload__tip"
              style="padding-left:10px;"
            >只能上传.txt/.pdf/.doc/.docx/.xls/.xlsx文件，且不超过20MB</span>
          </el-upload>-->
          <lessoUploader
            :baseUrl="baseUrl"
            :userInfo="userInfo"
            :deleteBtn="true"
            @fileError="fileError"
            @fileExceed="fileExceed"
            @fileAdded="fileAdded"
            @fileRemoved="fileRemoved"
            @fileSuccess="fileSuccess"
            @overSize="overSizeHandler"
            :multiple="true"
            :limits="5"
            :maxSize="20971520"
            :allowDuplicateUploads="false"
            @deleteFile="onFileDelete"
          >
            <div slot="upload-btn">
              <div class="slot_btn">选择附件</div>
            </div>
          </lessoUploader>
          <div v-if="files.length>0">
            <div
              class="uploaded_files"
              v-for="(file,index) in files"
              :key="index"
              @mouseenter="file.iconShow=true"
              @mouseleave="file.iconShow=false"
            >
              <div class="name" :title="file.name">
                <i class="el-icon-document"></i>
                {{file.name}}
              </div>
              <span class="state_icon">
                <i class="el-icon-circle-check" style="color:#67c23a" v-show="!file.iconShow"></i>
                <i class="el-icon-close" v-show="file.iconShow" @click="deletedFile(file)"></i>
              </span>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveQuestionData('save')" :loading="btnLoading">保存</el-button>
        <el-button type="primary" @click="saveQuestionData('releaser')" :loading="btnLoading">发布</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import lessoEditor from 'lesso-vue-editor'
import lessoUploader from 'lesso-file-upload/lessoUploader';
import constant from '@/public/constant'
import apienv from '@/api/env'
import Msg from '@/public/message'
export default {
  data () {
    return {
      // 富文本配置   
      editorOptions: {
        userName: this.$global.employeeName,
        userId: this.$global.userId,
        uploadUrl: apienv[constant.appenv].srm + 'uploadFastdfs/',
      },
      //   表单校验规则
      rules: {
        title: [
          { required: true, trigger: "change", message: "标题不能为空" }
        ],
        type: [
          { required: true, trigger: "change", message: "问题分类不能为空" }
        ],
        content: [
          { required: true, trigger: "change", message: "处理方法不能为空" }
        ]
      },
      //   element上传组件上传地址
      upload_url: this.$uploadUrl,
      //   文件上传地址
      baseUrl: apienv[constant.appenv].srm + 'uploadFastdfs/',
      //   用户信息
      userInfo: {
        userName: this.$global.user.employeeName,
        userId: this.$global.user.id,
        groupName: 'SRM'
      },
      //   优先级下拉
      priorityOptions: [
        { label: '普通', value: 0 },
        { label: '常见', value: 1 }
      ],
      //   级联配置
      cascaderProps: {
        checkStrictly: true,
        value: 'enumCode',
        label: 'enumName',
        children: 'childs'
      },
      btnLoading: false,
      //   上传文件列表
      attachmentList: []
    }
  },
  props: {
    addTab: {
      type: Function
    },
    dialogTitle: {
      type: String,
      default: '问题新增'
    },
    dialogVisible: {
      type: Boolean
    },
    parentOptions: {
      type: Array
    },
    ruleForm: {
      type: Object
    },
    files: {
      type: Array
    }
  },
  methods: {
    cascaderChange (val) {
      console.log(val)
    },
    // 取消编辑
    handleClose (val) {
      this.$emit('cancelEdit', val)
    },
    // 点击已上传文件钩子
    handlePreview (file) {
      //console.log(file);
    },
    // 文件移除钩子
    handleRemove (file, fileList) {
      //  if(this.attachmentList.length>0){
      //      for(let i in this.attachmentList) {
      //          if(this.attachmentList[i].uid==file.uid){
      //              this.attachmentList.splice(i,1)
      //          }
      //      }
      //  }
      //  console.log("已删除",this.attachmentList)
    },
    // 文件移除钱钩子
    beforeRemove (file, fileList) {
      const { status } = file
      if (status == 'success') {
        return new Promise((resolve, reject) => {
          this.$confirm("是否删除该附件？", "消息提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            distinguishCancelAndClose: true
          }).then(() => {
            if (file.id) {
              this.ruleForm.attachments.forEach(item => {
                if (item.ID == file.id) {
                  this.attachmentList.push(item)
                }
              })
              resolve()
            } else {
              for (let k in this.attachmentList) {
                if (this.attachmentList[k].uid == file.uid) {
                  this.attachmentList.splice(k, 1)
                }
              }
              resolve()
            }
          }).catch(() => {
            reject()
          })
        })
      } else {
        return true
      }
    },
    // 文件状态改变钩子
    change (file) {
      this.upload_url = this.$uploadUrl;
    },
    // 文件上传成功钩子
    uploadSuccess (response, file, fileList) {
      if (response.code == 1) {
        Msg.showSuccessMsg("上传成功")
        //保存文件信息
        let obj = {
          creator: this.$global.user.loginName,
          creatorId: this.$global.user.id,
          resourceType: 2
        }
        obj.size = file.size
        obj.url = response.rows[0].fileName
        obj.name = file.name
        obj.uid = file.uid
        this.attachmentList.push(obj)
      } else {
        Msg.showErrorMsg("操作失败！")
        this.$refs.upload.clearFiles()
      }
    },
    // 文件上传前钩子
    beforeAvatarUpload (file) {
      let fileType = file.name.substring(file.name.lastIndexOf('.') + 1)
      if (fileType) {
        let fy = fileType.toLowerCase();
        if (fy != "txt" && fy != "pdf" && fy != "doc" && fy != "docx" && fy != "xls" && fy != "xlsx") {
          this.$message({
            message: '上传文件类型只支持.txt/.pdf/.doc/.docx/.xls/.xlsx ！',
            type: 'warning'
          });
          return false;
        }
        const size = file.size / 1024 / 1024 < 20;
        if (!size) {
          this.$message({
            message: '上传模板大小不能超过 20MB!',
            type: 'warning'
          });
          return false
        }
      }
    },
    // 文件通过检查回调
    fileAdded (file) {
      let allFiles = [...this.files, ...this.attachmentList]
      if (allFiles.length > 4) {
        this.$message({
          message: '最多上传五个文件！',
          type: 'warning'
        })
        file.cancel();
      } else {
        for (var i in this.files) {
          if (this.files[i].md5 == file.md5) {
            this.$message({
              message: '请勿上传重复文件',
              type: 'warning'
            })
            file.cancel();
          }
        }
      }
    },
    // 删除文件
    onFileDelete (file, callback) {
      var that = this;
      this.$confirm("是否删除该附件？", "消息提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        distinguishCancelAndClose: true
      }).then(() => {
        // if (that.mode == "add") {
        callback(true);
        for (var i in that.attachmentList) {
          if (that.attachmentList[i].md5 == file.md5) {
            that.attachmentList.splice(i, 1);
          }
        }
        // }
      }).catch(() => { })
    },
    // 编辑时删除文件
    deletedFile (file, index) {
      this.$confirm("是否删除该附件？", "消息提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        distinguishCancelAndClose: true
      }).then(() => {
        let obj = {
          groupName: 'SRM',
          fileMd5: file.md5,
          uid: this.$global.user.id
        }
        this.$http.deletedFastdfsFile(obj).then(({ data }) => {
          if (data.code == 200) {
            Msg.showSuccessMsg('文件已删除')
            this.files.splice(index, 1)
            this.attachmentList.push(file)
          } else {
            Msg.showErrorMsg(data.msg)
          }
        }).catch(err => {
          Msg.showErrorMsg(err.data.message)
        })
      })
    },
    // 文件上传成功回调
    fileSuccess (file, message, chunk) {
      if (message.code === 200) {
        var obj = {
          creator: this.$global.user.loginName,
          creatorId: this.$global.user.id,
          resourceType: 2
        };
        obj.size = file.size;
        obj.url = file.viewPath;
        obj.md5 = file.md5;
        obj.name = file.name;
        this.attachmentList.push(obj);
      }
    },
    // 文件移除完回调
    fileRemoved (file, response) {
      if (response.code === 200) {
        for (let i = this.attachmentList.length - 1; i >= 0; i--) {
          if (this.attachmentList[i].md5 == file.md5)
            this.attachmentList.splice(i, 1);
        }
      }
    },
    // 文件超出大小回调
    overSizeHandler (file) { // 文件过大回调
      this.$message.warning("选择的文件大小不能超过20M")
    },
    //文件类型不合法回调
    onInvalidFile (file) {
      this.$message.warning('文件类型不合法')
    },
    // 文件上传失败回调
    fileError (file, message, chunk) {
      message = JSON.parse(message)
      this.$message.error(message.msg);
    },
    //文件个数超出限制
    fileExceed (files, fileList) {
      this.$message.warning('上传文件个数超出限制,最多只能上传5个文件')
    },
    // 保存数据
    saveQuestionData (operatType) {
      const { content } = this.ruleForm
      let editorDoc = document.querySelector('#ls_questionEdit')
      let text = editorDoc.querySelector('.w-e-text').innerText
      let img = editorDoc.querySelector('.w-e-text').getElementsByTagName('img')
      // 判断富文本内容是否为空   
      if (!content) {
        this.$message.error('处理方法不能为空')
        return
      } else {
        if (!text.trim() && img.length == 0) {
          this.$message.error('处理方法不能为空')
          return
        }
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const { type, id } = this.ruleForm
          let editType = ''
          let params = {
            ...this.ruleForm,
            type: Array.isArray(type) ? type[type.length - 1] : type,
            releaser: operatType == "save" ? '' : this.$global.user.employeeName,
            releaserId: operatType == "save" ? '' : this.$global.user.id,
            state: operatType == "save" ? 0 : 1,
            attachments: this.attachmentList
          }
          if (this.dialogTitle == '问题新增') {
            params.creator = this.$global.user.employeeName
            params.creatorId = this.$global.user.id
            editType = 'add'
          } else {
            params.modifyer = this.$global.user.employeeName
            params.modifyerId = this.$global.user.id
            params.id = id
            editType = 'edit'
          }
          this.ruleForm.attachments = this.attachmentList;
          this.btnLoading = true
          this.$http.saveQuestion(params).then(({ data }) => {
            this.btnLoading = false
            if (data.code == 1) {
              let msg = operatType == "save" ? '保存成功' : '发布成功'
              Msg.showSuccessMsg(msg)
              this.handleClose(editType)
            } else {
              Msg.showErrorMsg(data.info)
            }
          }).catch(err => {
            this.btnLoading = false
            Msg.showErrorMsg(err.data.message)
          })
        }
      })
    }
  },
  components: {
    lessoEditor,
    lessoUploader
  },
  beforeMount () {
  }
};
</script>

<style lang="less" scoped>
.m-view-questionEdit {
  /deep/ .el-dialog__wrapper {
    /deep/ .el-dialog {
      /deep/ .el-dialog__body {
        max-height: 400px;
        overflow: auto;
        .edit-ruleForm {
          /deep/.el-form-item {
            width: 600px;
          }
        }
      }
    }
  }
}
</style>